/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/
/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-03-29 16:26:48
 */
import { CENTEREVENTS, EventsRes } from '@amcax/base';
import { eventCenterManager } from '@app-base/common/events/EventCenterManager';
import { KEYBOARD_KEY } from '@app-cad/common/Constants';
import { userEvents } from '@app-cad/module';
import CmdInteractor from './CmdInteractor';

let cmdInteractor: CmdInteractor = null;

const init = ({ gallery }) => {
  registerEvents();

  cmdInteractor = new CmdInteractor();
  cmdInteractor.begin('LoadGallery', 'CAD');
  cmdInteractor.execute({ gallery });
};

const registerEvents = () => {
  eventCenterManager.activeEventCenter
    .setState('component-import')
    .on(CENTEREVENTS.KEYUP, keyupEvent);

  userEvents.on('componentMoveEnd', onComponentMoveEnd);
};
const unregisterEvents = () => {
  eventCenterManager.activeEventCenter
    .off(CENTEREVENTS.KEYUP, keyupEvent)
    .setDefault();

  userEvents.off('componentMoveEnd', onComponentMoveEnd);
};

const keyupEvent = (e: EventsRes<KeyboardEvent>) => {
  if (e.key === KEYBOARD_KEY.ESC) {
    destory();
  }
};
const onComponentMoveEnd = ({ placement }) => {
  cmdInteractor.execute({ placement });
  cmdInteractor.end();
  unregisterEvents();
};

const destory = () => {
  if (cmdInteractor) {
    cmdInteractor.abort();
    cmdInteractor = null;
    unregisterEvents();
  }
};

export const cmdComponentImport = {
  id: 'cmd-component-import',
  icon: 'commands/feature/import',
  label: 'command.component.import',
  invoke: init,
  destory: destory,
};
